﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboSdk;
using WeiboSdkSample.Classes;

namespace WeiboSdkSample.PageViews
{
    public partial class SsoSharePage : PhoneApplicationPage
    {
        private const string KEY_STATUS = "LastStatus";
        public SsoSharePage()
        {
            InitializeComponent();
        }

        private void img_Tapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (App.AccessToken != null)
            {
                return;
            }
            // 注意：保存当前的状态，以便微博回调时状态不丢失
            if (!string.IsNullOrEmpty(tbStatus.Text))
            {
                PersistHelper.SaveSettingToStorage(KEY_STATUS, tbStatus.Text);
            }
            WeiboAssociation.SsoAuth(SdkData.AppKey, SdkData.RedirectUri);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.AccessToken != null)
            {
                webImg.Opacity = 1.0;

                tbkUserName.Text = "已绑定,账号：" + App.Nickname;

                tbStatus.Text = PersistHelper.LoadSetttingFromStorage<string>(KEY_STATUS, "");
            }
            base.OnNavigatedTo(e);
        }


        private void sendIconButton_Click(object sender, EventArgs e)
        {
            if (App.AccessToken == null)
            {
                MessageBox.Show("请先授权~");
                return;
            }
            if (string.IsNullOrEmpty(tbStatus.Text.Trim()))
            {
                MessageBox.Show("请输入分享内容~");
                return;
            }

            grdSending.Visibility = Visibility.Visible;

            SdkNetEngine netEngine = new SdkNetEngine();
            var cmdBase = new cmdUploadMessage
            {
                status = this.tbStatus.Text,
                acessToken = App.AccessToken
            };
            netEngine.RequestCmd(SdkRequestType.UPLOAD_MESSAGE, cmdBase, requestCompleted);
        }

        void requestCompleted(SdkRequestType requestType, SdkResponse response)
        {
            Dispatcher.BeginInvoke(delegate
            {
                if (response.errCode == SdkErrCode.SUCCESS)
                {
                    grdSending.Visibility = Visibility.Collapsed;
                    PersistHelper.DeleteSetting(KEY_STATUS);
                    tbStatus.Text = "";
                    MessageBox.Show("发送成功");
                }
                else
                {
                    MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK);
                }
            });
        }
    }
}